<?php
namespace Admin\Model;
use Think\Model;
class ProductPackageModel extends Model {
	public function str_split_unicode($str, $l = 0) {
		if ($l > 0) {
			$ret = array();
			$len = mb_strlen($str, "UTF-8");
			for ($i = 0; $i < $len; $i += $l) {
				$ret[] = mb_substr($str, $i, $l, "UTF-8");
			}
			return $ret;
		}
		return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
	}
	/*正则过滤特殊字符*/
	public function replace_specialChar($strParam){
	    $char = "。、！？：；﹑•＂…‘’“”〝〞∕¦‖—　〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔！¡？¿﹖﹌﹏﹋＇´ˊˋ―﹫︳︴¯＿￣﹢﹦﹤‐­˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼（）";
	    $pattern = array(
		    "/[[:punct:]]/i", //英文标点符号
		    '/['.$char.']/u', //中文标点符号
		    '/[ ]{2,}/'
		);
		return preg_replace($pattern, '', $strParam);

	}

	/*套餐名中汉字转换为小写首字母*/
	public function getLowerName($name){
		$tempArr = $this->str_split_unicode($name);
		for ($i=0; $i < count($tempArr); $i++) { 
			if(preg_match('/['.chr(0xa1).'-'.chr(0xff).']/', $tempArr[$i])){
				$tempArr[$i] = strtolower(ff_letter_first($tempArr[$i]));
			}
		}
		for ($j=0; $j < count($tempArr); $j++) { 
			$package_code .= $tempArr[$j];
		}
		return 	$package_code;
	}

	/*根据产品id获取产品线缩写*/
	public function getProductLine_code($product_id){
		$map = array();
		$map['product_id'] = array('eq',$product_id);
		$product_line_code  = M('product')->where( $map )->getField("product_line_code");
		return $product_line_code;
	}

	/*处理套餐价格:套餐多个报价，多个报价之间用|分隔*/
	public function getPackagePrice($package_price){
		if(strstr($package_price, '；') || strstr($package_price, ';')){
			$search = array(" ","　","\n","\r","\t");
			$replace = array("","","","","");
			$package_price = str_replace($search, $replace, $package_price);
			$package_price = str_replace('；', '|', $package_price);
			$package_price = str_replace(';', '|', $package_price);
			if('|' == substr( $package_price, 0, 1 )){
				$package_price = substr($package_price, 1);
			}
			if('|' == substr( $package_price, -1 )){
				$package_price = substr($package_price,0,strlen($package_price)-1);
			}
		}
		return $package_price;
	}

	/*获取表中qy_deparment_id的最大值并自增1*/
	public function getMaxId(){
		$wheres = array();
		$wheres['is_deleted'] = array('neq',1);
		$linMax = (int)M("product_line")->where($wheres)->getField("max(qy_deparment_id)");
		$prodectMax = (int)M("product")->getField("max(qy_deparment_id)");
		$packageMax = (int)M("product_package")->where($wheres)->getField("max(qy_deparment_id)");
		$maxVal = $linMax>$prodectMax?($linMax>$packageMax?$linMax:$packageMax):($prodectMax>$packageMax?$prodectMax:$packageMax);
		return $maxVal+1;
	}

	/**添加套餐操作*/
	public function add_package( $add_data, $addService ){
		$r = array('d'=>NULL,'i'=>'','r'=>0);
		if( !$add_data['name'] || !$add_data['product_id'] ){
			$r['i'] = "表单信息获取失败";
			return $r;
		}else{
			//套餐名中汉字转换为小写首字母
			$name =  $this->replace_specialChar($add_data['name']); //过滤掉特殊字符
			$package_code = $this->getLowerName($name);
			//同步企业号通讯录
			$map = array();
			$map['product.product_id'] = array('eq', $add_data['product_id']);
			$map['qy.is_deleted'] = array('neq', 1);
			$qyInfo = M("product")
					->field("product.qy_deparment_id,product.product_line_code,qy.qy_code,product.name")
					->join("qy on qy.product_line_code=product.product_line_code")
					->where($map)
					->select();
			if($qyInfo){
				$qyhObj = C("QYH");
				$maxId = $this->getMaxId();//获取数据表中qy_deparment_id的最大值并自增1
				for ($i=0; $i < count($qyInfo); $i++) {
					foreach ($qyhObj as $qyk => $qyval) {
						//判断企业号是否在配置文件中
						if($qyval['corpCode'] == $qyInfo[$i]['qy_code']){
							$MQy[$i] =  new \Common\ORG\Qy($qyInfo[$i]['qy_code']);
							$queryDate[$i] = $MQy[$i]->queryDepartment((int)$qyInfo[$i]['qy_deparment_id']);
							if($queryDate[$i]){
								foreach ($queryDate[$i]['data'] as $Dk => $Dval) {
									$queryDateArr[] = $Dval;
								}
							}
							//判断该产品在企业号中是否已经添加
							if($queryDate[$i]['rcode'] && $queryDateArr[0]['name']==$qyInfo[$i]['name']){//产品存在，直接添加套餐
								$returnDate[$i] = $MQy[$i]->createDepartment($add_data['name'], $qyInfo[$i]['qy_deparment_id'], $maxId);
								if($returnDate[$i]['rcode'] == 0){
									$r[$i]['r'] = 0;
									$r[$i]['i'] = '同步企业号通讯录失败-'+$returnDate[$i]['msg'];
									return $r[$i];
								}
							}
						}
					}
				}
				//添加套餐对应的服务
				$addServiceArr = explode(",", $addService);
				foreach ($addServiceArr as $sk => $sval) {
					$add[$sk] = array();
					$add[$sk]['service_id'] = $sval;
					$add[$sk]['package_code'] = $package_code;
					$addSerToPack[$sk] = M("package_service")->add($add[$sk]);
					if(!$addSerToPack[$sk]){
						$r['i'] = '套餐添加服务失败';
						return $r;
					}
				}
				$d = array();
				$d['name'] = $add_data['name'];
				$d['product_id'] = $add_data['product_id'];
				$d['package_service'] = $add_data['package_service'];
				$d['package_remark'] = $add_data['package_remark'];
				$d['product_line_code'] = $this->getProductLine_code($add_data['product_id']);
				$d['package_code'] = $package_code;
				$d['qy_deparment_id'] = $maxId;
				$d['is_deleted'] = 0;
				$d['package_multi_prices'] = $this->getPackagePrice($add_data['package_multi_prices']);
				$addID = $this->add($d);
				if($addID){
					$r['d']=1;
					$r['r']='ok';
				}else{
					$r['i'] = '套餐添加失败！';
				}
			}else{
				$r['i'] = '获取企业号信息失败！';
			}
		}
		return $r;
	}

	/** 更新产品操作*/
	public function update_Package($edit_data){
		$r = array('d'=>NULL,'i'=>'','r'=>0);
		$wheres = array();
		$wheres['package_code'] = array('eq', $edit_data['package_code'] );
		$dpackage = $this->where( $wheres )->find();
		if(!$dpackage){
			$r['i'] = "套餐信息获取失败";
		}else{
			$d['name'] = $edit_data['name'];
			$d['package_service'] = (int)$edit_data['package_service'];
			$d['package_multi_prices'] = $this->getPackagePrice($edit_data['package_multi_prices']);
			$d['package_remark'] = $edit_data['package_remark'];
			$d['product_id'] = $edit_data['product_id'];
			$product_line_code = $this->getProductLine_code($edit_data['product_id']);
			$editOrNot = $this->where( $d )->find();
			$serviceList = M("package_service")->field("service_id")->where($wheres)->select();//获取套餐对应的原服务列表
			foreach ($serviceList as $key => $value) {
				$serviceListArr[$key] = $value['service_id'];
			}
			$editServiceArr = explode(",", $edit_data['editService']);
			if(!$editOrNot || $serviceListArr != $editServiceArr){	//修改了套餐信息
				if( $dpackage['name']!=$edit_data['name'] || $dpackage['product_id']!=$edit_data['product_id'] ){
					//修改套餐名称或归属产品，同步企业号通讯录
					$map = array();
					$map['product.product_id'] = array('eq', $edit_data['product_id']);
					$map['qy.is_deleted'] = array('neq', 1);
					$qyInfo = M("product")
							->field("product.product_line_code,product.qy_deparment_id as product_deparment_id,qy.qy_code")
							->join("qy on qy.product_line_code=product.product_line_code")
							->where($map)
							->select();
					if($qyInfo){
						$qyhObj = C("QYH");		//读取配置文件中的企业号
						for ($i=0; $i < count($qyInfo); $i++) {
							foreach ($qyhObj as $qyk => $qyval) {
								//判断企业号是否在配置文件中
								if($qyval['corpCode'] == $qyInfo[$i]['qy_code']){
									$MQy[$i] =  new \Common\ORG\Qy($qyInfo[$i]['qy_code']);
									//判断是否编辑套餐名，若更改同步企业号通讯录
									if( $dpackage['name']!=$edit_data['name'] ){
										$returnDate[$i] = $MQy[$i]->updateDepartment($dpackage['qy_deparment_id'], $edit_data['name']);
										if($returnDate[$i]['rcode'] == 0){
											$r['r'] = 0;
											$r['i'] = "同步企业号通讯录失败—".$returnDate[$i]['msg'];
											return $r;
										}
									}
									//判断是否更改所属产品，若更改同步企业号通讯录
									if( $dpackage['product_id']!=$edit_data['product_id'] ){
										$queryDate2[$i] = $MQy[$i]->deleteDepartment($dpackage['qy_deparment_id']);
										if($queryDate2[$i]['rcode']){
											$returnDate2[$i] = $MQy[$i]->createDepartment($edit_data['name'], $qyInfo[$i]['product_deparment_id'], $dpackage['qy_deparment_id']);
											if($returnDate2[$i]['rcode'] == 0){
												$r['r'] = 0;
												$r['i'] = '同步企业号通讯录失败-'.$returnDate2[$i]['msg'];
												return $r;
											}
										}else{
											$r['r'] = 0;
											$r['i'] = '同步企业号通讯录失败！';
											return $r;
										}
									}
								}
							}
						}
					}else{
						$r['i'] = '获取企业号信息失败！';
					}
				}
				if($serviceListArr != $editServiceArr){		//修改套餐对应的服务
					$delArr = M("package_service")->where($wheres)->delete();
					foreach ($editServiceArr as $sk => $sval) {
						$edit[$sk] = array();
						$edit[$sk]['service_id'] = $sval;
						$edit[$sk]['package_code'] = $edit_data['package_code'];
						$editSerToPack[$sk] = M("package_service")->add($edit[$sk]);
						if(!$editSerToPack[$sk]){
							$r['i'] = '编辑套餐对应服务信息失败！';
							return $r;
						}
					}
				}
				if(!$editOrNot){ //更改套餐信息
					$editID = $this->where( $wheres )->save( $d );
					if($editID){
						$r['r'] = 1;
						$r['d'] = $this->where( $wheres )->find();
						$r['i'] = 'OK';
					}else{
						$r['i'] = '编辑套餐失败';
					}
				}else{
					$r['r'] = 1;
					$r['d'] = $this->where( $wheres )->find();
				}
			}else{
				$r['r'] = 2;	//未修改套餐信息和服务信息
			}
		}
		return $r;
	}
	
	/** 删除套餐操作*/
	public function delete_Package( $package_code, $qy_deparment_id ){
		$r = array('r'=>0,'i'=>'server error','d'=>NULL );
		if( !$package_code ){
			$r['i'] = '参数错误！';
			return $r;
		}else{
			$wheres1 = array();
			$wheres1['product_package.package_code'] = array('eq', $package_code);
			//判断该套餐下是否存在关联的栏目
			$dlist1 = M("product_package")
				  ->join('qy_app_package  as  qy  on  product_package.package_code = qy.package_code')
				  ->where( $wheres1 )
				  ->select();
			//判断该套餐下是否存在关联的订户
			$wheres2 = array();
			$wheres2['qy_subscriber_status'] = array('eq',10);	//用户状态为服务中
	  		$dlist2 = M("qy_subscriber")->field("qy_subscriber_department")->where($wheres2)->select();
	  		if($dlist1){
				$r['r'] = 2;
				$r['i'] = "该套餐存在关联的栏目，暂时无法删除！";
				return $r;
			}
	  		if($dlist2){
	  			for ($i=0; $i < count($dlist2); $i++) {
		  			$dlist2[$i]['departmentArr'] = explode(',',$dlist2[$i]['qy_subscriber_department']);
		  			if($dlist2[$i]['departmentArr']){
		  				for ($j=0; $j < count($dlist2[$i]['departmentArr']); $j++) {
			  				if($qy_deparment_id == (int)$dlist2[$i]['departmentArr'][$j]){
			  					$r['r'] = 3;
								$r['i'] = "该产品存在关联的订户，暂时无法删除！";
								return $r;
			  				}
			  			}
		  			}
		  		}
	  		}
			if(!$dlist1){
				$where = array();
				$where['package_code'] = array('eq', $package_code);
				//同步企业号通讯录
				$map = array();
				$map['product_package.qy_deparment_id'] = array('eq', $qy_deparment_id);
				$map['qy.is_deleted'] = array('neq', 1);
				$qyInfo = M("product")
						->field("product_package.qy_deparment_id,product.product_line_code,qy.qy_code")
						->join("qy on qy.product_line_code=product.product_line_code")
						->join("product_package on product_package.product_id=product.product_id")
						->where($map)
						->select();
				if($qyInfo){
					$qyhObj = C("QYH");
					for ($i=0; $i < count($qyInfo); $i++) {
						foreach ($qyhObj as $qyk => $qyval) {
							//判断企业号是否在配置文件中
							if($qyval['corpCode'] == $qyInfo[$i]['qy_code']){
								$MQy[$i] =  new \Common\ORG\Qy($qyInfo[$i]['qy_code']);
								$returnDate[$i] = $MQy[$i]->deleteDepartment($qyInfo[$i]['qy_deparment_id']);
								if($returnDate[$i]['rcode'] == 0){
									$r['r'] = 0;
									$r['i'] = '同步企业号通讯录失败-'.$returnDate[$i]['msg'];
									return $r;
								}
							}
						}
					}
					//删除关联的服务
					$delSerToPack = M("package_service")->where($where)->delete();
					if($delSerToPack){
						$d = array();
						$d['is_deleted'] = 1;
						$d['package_code'] = $package_code.substr((string)time(), -4);
						$delID = $this->where( $where )->save($d);
						if($delID){
							$r['r'] = 1;
	 						$r['i'] = 'OK';
						}else{
							$r['i'] = '删除失败！';
							$r['r'] = 0;
							return $r;
						}
					}else{
						$r['i'] = '删除关联的服务失败！';
						$r['r'] = 0;
						return $r;
					}
				}else{
					$r['i'] = '获取企业号信息失败！';
				}
			}
		}
		return $r;
	}


}